#include <stdio.h>
#include <stdlib.h>
#include "DynamicArray.h"

#define true 1
#define false 0

int Initialize(DynamicArray *array)
{
    array->dp = (ElementType *)malloc(sizeof(ElementType) * array->size);
    if(array->dp == NULL)
    {
        printf("malloc error!\n");
        return false;
    }
    return true;
}

void FreeArray(DynamicArray *array)
{
    if(array->dp != NULL)
    {
        free(array->dp);
        array->dp = NULL;
        array->len = 0;
    }
}

int ReallocArray(DynamicArray *array)
{
    ElementType *temp = array->dp;
    array->size = array->size * 2;
    array->dp = (ElementType *)malloc(sizeof(ElementType) * array->size);
    if(array->dp == NULL)
    {
        printf("ReallocArray error!\n");
        array->dp = temp;
        array->size = array->size / 2;
        return false;
    }

    for(int i = 0; i < array->len; i++)
    {
        array->dp[i] = temp[i];
    }

    Free(temp);
    return true;

}

int InsertArray(DynamicArray *array,ElementType element)
{
    if(array->len == array->size)
    {
        if(ReallocArray(array) == false)
        {
            printf("can not  contain more elements!\n");
            return false;
        }
    }
    array->dp[array->len] = element;
    array->len++;
    return true;
}